<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\analysis\material;

use app\command\BaseWork;
use app\enum\AnalysisEnum;
use app\service\analysis\data\material\MaterialAreaMonthStatService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;

class MaterialAreaMonthStatWork extends BaseWork
{
    public const REDIS_TASK_KEY = AnalysisEnum::TASK_QUEUE_LIST['area_month_stat'];

    protected function configure()
    {
        // 指令配置
        $this->setName('analysis_material_area_month_stat_work');
        // 设置参数
        $this->setDescription('数据分析-素材月汇总')
            ->setHelp('php think analysis_material_area_month_stat_work');
    }

    /**
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);

        $redis = Cache::store('redis')->handler();
        $fields = $redis->hKeys(self::REDIS_TASK_KEY);
        if ($fields) {
            // 超过5min就停止
            $t = time();
            $runTime = 5 * 60;
            foreach ($fields as $field) {
                if (time() - $t > $runTime) {
                    continue;
                }
                $data = $redis->hGet(self::REDIS_TASK_KEY, $field);
                $arr = json_decode($data, true);
                $obj = new MaterialAreaMonthStatService();
                try {
                    $this->getOutputMessage('同步[' . $arr[0] . ']开始');
                    if (! $obj->runTask($arr)) {
                        $this->getOutputMessage('同步[' . $arr[0] . ']失败:' . $obj::getError(0));
                    } else {
                        $redis->hDel(self::REDIS_TASK_KEY, $field);
                    }
                    $this->getOutputMessage('同步[' . $arr[0] . ']完成');
                } catch (\Exception $e) {
                    $this->getOutputMessage('错误：' . $e->getMessage());
                    echo $e->getLine() . PHP_EOL;
                    echo $e->getFile() . PHP_EOL;
                    echo $e->getTraceAsString() . PHP_EOL;
                }
            }
        }
        $this->getOutputMessage('素材追加结束');
    }
}
